//
//  UITextField+Extension.swift
//  SK_BasePrivateProject
//
//  Created by Regina on 2018/10/08.
//  Copyright © 2018年 Regina. All rights reserved.
//

import Foundation
import UIKit

extension UITextField  {
    
    func trimmingNeedlessCharacters(_ length: Int) {
        
        if self.markedTextRange != nil { return }
        if self.text == nil { return }
        
        //当前光标的位置（后面会对其做修改）
        let cursorPostion =  self.offset(from: self.endOfDocument, to: self.selectedTextRange!.end)
        
        var text = self.text!
        //如果长度超过限制则直接截断
        text = text.subStringToIndex(length) ?? ""
        self.text = text
        //让光标停留在正确位置
        let targetPostion =  self.position(from: self.endOfDocument, offset: cursorPostion)!
        self.selectedTextRange =  self.textRange(from: targetPostion, to: targetPostion)
        
    }
    
    func trimmingNeedlessCharacters(_ length: Int, byReplacingMatches pattern: String) {
        
        if self.markedTextRange != nil { return }
        if self.text == nil { return }
        
        //当前光标的位置（后面会对其做修改）
        let cursorPostion =  self.offset(from: self.endOfDocument, to: self.selectedTextRange!.end)
       
        var text = self.text!
        text = text.replaceWithRegular(pattern: pattern, with: "")

        //如果长度超过限制则直接截断
        text = text.subStringToIndex(length) ?? ""
        self.text = text
        //让光标停留在正确位置
        let targetPostion =  self.position(from: self.endOfDocument, offset: cursorPostion)!
        self.selectedTextRange =  self.textRange(from: targetPostion, to: targetPostion)
    }
    
    func setLeftSpace(_ space: CGFloat) {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: space, height: self.height))
        view.backgroundColor = UIColor.clear
        
        self.leftView = view
        self.leftViewMode = .always
    }
    
    func setRightSpace(_ space: CGFloat) {
        
    }
}
